<template>
  <el-form
    ref="ruleForm"
    :inline="true"
    :model="ruleForm"
    :rules="rules"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-row>
      <el-form-item label="书名" prop="bookName">
        <el-input v-model="ruleForm.bookName" style="width: 800px" />
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="图片" prop="cover">
        <el-input v-model="ruleForm.cover" style="width: 200px" />
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="定价" prop="price">
        <el-input v-model="ruleForm.price" style="width: 200px" />
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="折扣" prop="discount">
        <el-input v-model="ruleForm.discount" style="width: 200px" />
      </el-form-item>
    </el-row>
    <el-row>
      <el-form-item label="当前价格" prop="nowPrice">
        <el-input v-model="ruleForm.nowPrice" style="width: 200px" />
      </el-form-item>
    </el-row>

    <el-form-item label="作者" prop="author">
      <el-input v-model="ruleForm.author" style="width: 200px" />
    </el-form-item>
    <el-form-item label="出版社" prop="press" style="margin-left: 10px">
      <el-input v-model="ruleForm.press" style="width: 200px" />
    </el-form-item>

    <el-row>
      <el-form-item label="出版时间" required>
        <el-col :span="11">
          <el-form-item prop="publishingTime">
            <el-date-picker
              v-model="ruleForm.publishingTime"
              type="date"
              placeholder="选择日期"
              style="width: 200px;"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="印刷时间" required>
        <el-col :span="11">
          <el-form-item prop="printingTime">
            <el-date-picker
              v-model="ruleForm.printingTime"
              type="date"
              placeholder="选择日期"
              style="width: 200px;"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="商品分类" prop="categories">
        <el-cascader v-model="ruleForm.categories" expand-trigger="hover" :options="catelist" :props="cateProps" clearable change-on-select @change="handleChange" />
      </el-form-item>
    </el-row>

    <el-row>
      <el-form-item label="商品封面" name="3">
        <!-- action 表示图片要上传到的后台API地址 -->
        <el-upload
          action=""
          :limit="limitNum"
          :file-list="fileList"
          :auto-upload="true"
          :http-request="uploadFile"
          :on-exceed="exceedFile"
          :on-change="fileChange"
          :before-upload="beforeUploadFile"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-error="handleError"
        >
          <el-button size="small" type="primary">上传封面</el-button>
          <div slot="tip" class="el-upload__tip">只能上传一份jpg/jpeg/png文件，且不超过5M</div>
        </el-upload>
      </el-form-item>
      <!-- 图片预览 -->
      <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
        <img :src="previewPath" alt="" class="previewImg">
      </el-dialog>
    </el-row>

    <el-form-item style="margin-left: 100px">
      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>

  </el-form>

</template>

<script>
import userApi from '@/api/user'
export default {
  data() {
    return {
      // :model绑定对象
      ruleForm: {
        bookName: '',
        cover: '',
        price: '',
        discount: '',
        nowPrice: '',
        author: '',
        press: '',
        publishingTime: '',
        printingTime: '',
        categories: []
        // // 上传图片的临时路径数组（对象）
        // pics: [],
      },
      // :rules绑定校验规则
      rules: {
        bookName: [
          { required: true, message: '请输入书名', trigger: 'blur' },
          { min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }
        ],
        cover: [
          { required: false, message: '', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'change' }
        ],
        discount: [
          { required: false, message: '请输入折扣', trigger: 'change' }
        ],
        nowPrice: [
          { required: false, message: '请输入当前价格', trigger: 'change' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'change' }
        ],
        press: [
          { required: true, message: '请输入出版社', trigger: 'change' }
        ],
        publishingTime: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        printingTime: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        categories: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]

      },
      // 商品分类列表
      catelist: [],
      cateProps: {
        label: 'title',
        value: 'id',
        children: 'children'
      },
      previewPath: '',
      previewVisible: false,
      limitNum: 1, // 上传时，同时允许上传的最大数
      fileList: [] // 文件列表
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`)
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.fileList.push(file.raw)
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 5
      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return isIMAGE && isLt1M
    },
    // 处理图片预览效果
    handlePreview() {
      this.previewPath = this.ruleForm.cover
      this.previewVisible = true
      // console.log(this.previewPath)
    },
    // 处理移除图片的操作
    handleRemove(file, fileList) {
      this.ruleForm.cover = null
      if (fileList.length === 0) {
        this.fileList = []
      } else {
        const dl = this.fileList.indexOf(file)
        this.fileList.splice(dl, 1)
      }
    },
    // 监听图片上传成功的事件
    handleSuccess(res) {
      this.$message.success('图片上传成功')
      this.ruleForm.cover = res.data.data.url
    },
    // 文件上传失败时的钩子
    handleError() {
      this.$message.error('图片上传失败')
    },

    // 手动上传
    uploadFile() {
      if (this.fileList.length === 0) {
        this.$message.warning('请上传文件')
      } else {
        const form = new FormData()
        form.append('file', this.fileList[0])
        // console.log(form.get('file'))
        // console.log(typeof form)
        userApi.uploadPics(form).then(res => {
          if (res.data.code === 200) {
            console.log('图片上传成功')
            // console.log(res.data.data)
            this.handleSuccess(res)
          }
        }, err => {
          this.handleError()
          console.log(err)
        })
      }
    },

    getYMDHMS(timestamp) {
      const time = new Date(timestamp)
      const year = time.getFullYear()
      let month = time.getMonth() + 1
      let date = time.getDate()
      let hours = time.getHours()
      let minute = time.getMinutes()
      let second = time.getSeconds()

      if (month < 10) { month = '0' + month }
      if (date < 10) { date = '0' + date }
      if (hours < 10) { hours = '0' + hours }
      if (minute < 10) { minute = '0' + minute }
      if (second < 10) { second = '0' + second }
      return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
    },
    // 获取商品分类数据
    async getCateList() {
      await userApi.getAllCategory().then(res => {
        // console.log(res.data.data.data)
        // this.$message.success('预加载获取分类成功！')
        this.catelist = res.data.data.data
      }, err => {
        // this.$message.error('获取失败')
        console.log(err)
      })
    },

    // 级联选择器选中项变化范围
    handleChange() {
      if (this.ruleForm.categories.length !== 2) {
        this.ruleForm.categories = []
      }
    },

    // 添加图书
    submitForm(formName) {
      var postData = {
        'author': this.ruleForm.author,
        'bookName': this.ruleForm.bookName,
        'cover': this.ruleForm.cover,
        'press': this.ruleForm.press,
        'price': this.ruleForm.price,
        'printingTime': this.getYMDHMS(this.ruleForm.printingTime),
        'publishingTime': this.getYMDHMS(this.ruleForm.publishingTime),
        'categories': this.ruleForm.categories
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi.newAddBook(postData).then(res => {
            if (res.data.code === 200) {
              this.$message.success('添加商品成功')
              this.$router.push('/bookSearch')
            }
          }, err => {
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>

</style>
